# Autosub Db.py - http://code.google.com/p/auto-sub/
#
# The Autosub downloadSubs module
#

import logging
import urllib2

import autosub

log = logging.getLogger('thelogger')



class downloadSubs():
    """
    Check the TODOWNLOADQUEUE and try to download everything in it.
    """
    def run(self):
        log.debug("downloadSubs: Something called downloadSubs, Starting downloadSubs")
        if autosub.TODOWNLOADQUEUELOCK or autosub.WANTEDQUEUELOCK:
            log.debug("downloadSubs: Exiting, another threat is using the queues")
            return False
        else:
            autosub.TODOWNLOADQUEUELOCK = True
            autosub.WANTEDQUEUELOCK = True
        
        dbItems = autosub.Helpers.ReadDb()
        
        for index, dbItem in enumerate(dbItems):
            
            videofile = dbItem['videofile']
            
            if dbItem['nlwanted'] == 2:
                if not (autosub.Helpers.checkAPICalls()):
                    log.debug("downloadSubs: Out of our api calls for now.")
                    autosub.TODOWNLOADQUEUELOCK = False
                    autosub.WANTEDQUEUELOCK = False
                    return None
                log.debug('downloadSubs: downloading a dutch subtitle')
                nlsrtfile = dbItem['nlsrtfile']
                nldownloadlink = dbItem['downloadedsubnl']
                try:
                    req = urllib2.Request(nldownloadlink)
                    req.add_header("User-agent", autosub.USERAGENT)
                    log.debug("downloadSubs: Trying to download subtitle %s" %nldownloadlink) 
                    response = urllib2.urlopen(req,None,autosub.TIMEOUT) 
                    autosub.Helpers.checkAPICalls(use=True)
                    try:
                        open(nlsrtfile, 'w').write(response.read())
                        log.info("downloadSubs: DOWNLOADED: %s" % nlsrtfile)
                        log.debug("downloadSubs: Updating database status to downloaded.")
                        autosub.Helpers.updateStatus(dbItem['episodeid'], 0, 'nl')
                        if dbItem['enwanted'] == 4:
                            autosub.Helpers.updateStatus(dbItem['episodeid'], 0, 'en')
                        
                        if autosub.POSTPROCESSCMD:
                            postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + nlsrtfile + '" "' + videofile + '"'
                            log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
                            log.info("downloadSubs: Running PostProcess")
                            postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
                            if postprocesserr:
                                log.error("downloadSubs: PostProcess: %s" % postprocesserr)
                            log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
                    except:
                        log.error("downloadSubs: Error while writing subtitle file. Destination: %s" % nlsrtfile)
                    
                except:
                    log.error("downloadSubs: The server returned an error for request %s" % nldownloadlink)
                
                
            
            if dbItem['enwanted'] == 2:
                if not (autosub.Helpers.checkAPICalls()):
                    log.debug("downloadSubs: Out of our api calls for now.")
                    autosub.TODOWNLOADQUEUELOCK = False
                    autosub.WANTEDQUEUELOCK = False
                    return None
                log.debug('downloadSubs: downloading a english subtitle')
                ensrtfile = dbItem['ensrtfile']
                endownloadlink = dbItem['downloadedsuben']                
                try:
                    req = urllib2.Request(endownloadlink)
                    req.add_header("User-agent", autosub.USERAGENT)
                    log.debug("downloadSubs: Trying to download subtitle %s" %endownloadlink)  
                    response = urllib2.urlopen(req,None,autosub.TIMEOUT)
                    autosub.Helpers.checkAPICalls(use=True) 
                    try:
                        open(ensrtfile, 'w').write(response.read())
                        log.info("downloadSubs: DOWNLOADED: %s" % ensrtfile)
                        log.debug("downloadSubs: Updating database status to downloaded.")
                        autosub.Helpers.updateStatus(dbItem['episodeid'], 0, 'en')
                        if autosub.POSTPROCESSCMD:
                            postprocesscmdconstructed = autosub.POSTPROCESSCMD + ' "' + ensrtfile + '" "' + videofile + '"'
                            log.debug("downloadSubs: Postprocess: running %s" % postprocesscmdconstructed)
                            log.info("downloadSubs: Running PostProcess")
                            postprocessoutput, postprocesserr = autosub.Helpers.RunCmd(postprocesscmdconstructed)
                            if postprocesserr:
                                log.error("downloadSubs: PostProcess: %s" % postprocesserr)
                            log.debug("downloadSubs: PostProcess Output:% s" % postprocessoutput)
                    except:
                        log.error("downloadSubs: Error while writing subtitle file. Destination: %s" % ensrtfile)
                except:
                    log.error("downloadSubs: The server returned an error for request %s" % endownloadlink)
        
        log.info("downloadSubs: Round of download subs is done!")
        autosub.TODOWNLOADQUEUELOCK = False
        autosub.WANTEDQUEUELOCK = False
        return True
